<?php
declare (strict_types = 1);

namespace app\api\middleware;

use app\common\model\ServerException;
use app\common\model\TokenException;
use app\common\model\Users;
use think\Response;

class User
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next):Response
    {

        $ignore_route = ['index/getIndexGoods', 'goods/detail','index/searchLog'];
        $rule=$request->rule();
        $route = $rule->getRoute();
        $data = $request->post();
//        if(input('get.no_encrypt') == 1){
//            $request_data = $data;
//        }else{
//            $request_data = $data['body'];
//        }


        try {
            //判断用户是否登录
            if(!isset($data['token']) || $data['token'] == "undefined"){
                throw new TokenException('用户未登录');
            }
            //验证token的有效性
            $user = Users::fromToken($data['token']);
        }catch (TokenException $e){
            if(in_array($route, $ignore_route)){
                $user = [];
            }else{
                throw new TokenException('用户未登录');
            }
        }
        $request->user_info = $user;
        return $next($request);
    }
}
